package nl.vu.few.ibivu.biomodels.client.activity;

import nl.vu.few.ibivu.biomodels.client.event.LoginStateChangedEvent;
import nl.vu.few.ibivu.biomodels.client.event.LoginStateChangedEventHandler;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastEvent;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastType;
import nl.vu.few.ibivu.biomodels.client.place.WelcomePlace;
import nl.vu.few.ibivu.biomodels.client.presenter.Presenter;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.inject.Inject;


public abstract class PresenterActivity extends AbstractActivity implements Presenter {

	protected PlaceController placeController;
	protected EventBus eventBus;
	protected boolean loginRequired;
	private HandlerRegistration registration;
	
	@Inject
	public PresenterActivity(EventBus eventBus, PlaceController placeController) {
		super();
		this.eventBus = eventBus;
		this.placeController = placeController;
		this.loginRequired = false;
		registration = LoginStateChangedEvent.register(this.eventBus, new LoginStateChangedEventHandler() {

			@Override
			public void onUserLogin(LoginStateChangedEvent event) {
				// Nothing Interesting!
			}

			@Override
			public void onUserLogout(LoginStateChangedEvent event) {
				if (loginRequired) {
					GWT.log("Leaving protected page!");
					goTo(new WelcomePlace());
				}
			}

		});
	}

	@Override
	public void onCancel() {
		// Avoid that the current presenter receives messages while waiting to be disposed
		if (registration != null) registration.removeHandler();
		super.onCancel();
	}

	@Override
	public void onStop() {
		// Avoid that the current presenter receives messages while waiting to be disposed
		if (registration != null) registration.removeHandler();
		super.onStop();
	}
	
	@Override
	public void goTo(Place place) {
		placeController.goTo(place);
	}

	public boolean isLoginRequired() {
		return loginRequired;
	}


	@Override
	public void broadcastMessage(MessageBroadcastType type, String message) {
		eventBus.fireEvent(new MessageBroadcastEvent(type, message));
	}



	public void setLoginRequired(boolean loginRequired) {
		this.loginRequired = loginRequired;
	}	
	
}
